// const { request } = require("express")

var baseurl = 'http://localhost:9528'
window.onload = function () {
    // 动态样式
    let sidebarUl = document.querySelector('.sidebar ul')
    let contentOl = document.querySelector('.content ol')
    let footer = document.querySelector('.footer')
    sidebarUl.style.height = document.documentElement.clientHeight - footer.offsetHeight - sidebarUl.offsetTop + 'px'
    contentOl.style.height = document.documentElement.clientHeight - footer.offsetHeight - contentOl.offsetTop + 'px'
    let content = document.querySelector('.content')
    content.style.width = document.documentElement.clientWidth - sidebarUl.offsetWidth - 40 + 'px'

    // 点击选规格
    var mask = document.querySelector('.mask')
    var menuname = document.querySelector('.detail h4')
    var img = mask.querySelector('.detail>img')
    var speces = mask.querySelector('.spec')
    var kinds = mask.querySelector('.kind')
    var addcartBtn = document.querySelector('.addcart')
    // 点击选规格
    contentOl.onclick = e => {
        var target = e.target
        if (target.tagName === 'INPUT' && target.type === 'button') {
            // 商品名称
            menuname.innerText = target.dataset.menuname
            // 图片显示
            img.src = target.previousElementSibling.previousElementSibling.src
            // 获取规格和种类数据
            let { spec, kind } = target.dataset
            // 规格 
            var speceshtml = ''
            // 渲染规格
            spec.split('=====').forEach(item => {
                speceshtml += `
                    <p>${item}</p>
                `
            })
            speces.innerHTML = speceshtml
            speces.children[0].className = 'active'
            // 种类
            var kindshtml = ''
            // 渲染种类
            kind.split('=====').forEach(item => {
                kindshtml += `
                    <p>${item}</p>
                `
            })
            kinds.innerHTML = kindshtml
            kinds.children[0].className = 'active'
            // 遮罩显示
            mask.style.display = 'block'


            // 获取商品ID - 放在添加购物车的按钮
            addcartBtn.setAttribute('data-id', target.dataset.id)
        }
    }
    // 切换规格
    speces.onclick = spedAndKindTab
    kinds.onclick = spedAndKindTab

    // 关闭遮罩
    var closeBtn = document.querySelector('.close')
    closeBtn.onclick = e => {
        mask.style.display = 'none'
    }


    // 添加购物车
    // 获取底部购物车页面
    var cartBox = document.querySelector('.cart')
    addcartBtn.onclick = function (e) {
        // 组合添加购物车需要的规格和种类
        // popup.msg('添加成功', () => {
        //     mask.style.display = 'none'
        //     // 让底部购物车显示
        //     cartBox.style.display = 'flex'

        // })

        let username = getCookie('username')
        if (!username) {
            popup.msg('请先登录！')
            return
        }
        // 发请求添加购物车
        // 获取规格
        let spec = document.querySelector('.spec p.active').innerText
        let kind = document.querySelector('.kind p.active').innerText
        request({
            url: '/front/api/cart/add',
            method: 'post',
            data: {
                userId: getCookie('userId'),
                dishId: addcartBtn.dataset.id,
                number: 1,
                speandkind: spec + '=====' + kind
            },
            headers: {
                Authorization: localStorage.getItem('token')
            }
        }).then(res => {
            // console.log(res);
            mask.style.display = 'none'
            // 让底部购物车显示
            cartBox.style.display = 'flex'

            //发送请求获取购物车数量
            request({
                url: '/front/api/cart/getnum/' + getCookie('userId'),
                headers: {
                    Authorization: localStorage.getItem('token')
                }
            }).then(res => {
                // console.log(res);
                if (res.error_code === 200) {
                    document.querySelector('.cart .cartnum').innerText = res.data.number
                }
            })


        })

    }

    // 底部导航
    var footerNav = document.querySelectorAll('.footer>div')
    for (var a = 0; a < footerNav.length; a++) {
        footerNav[a].onclick = function () {
            location.href = this.dataset.url
        }
    }

    // 点击购物车图标跳转
    document.querySelector('.carticon>i.iconfont').onclick = e => {
        location.href = '/cart.html'
    }

    // 发请求获取所有分类
    request({
        url: '/front/api/cat/getall'
    }).then(res => {
        // console.log(res);
        if (res.error_code === 200) {
            // 渲染界面
            let fragment = document.createDocumentFragment()
            res.data.cats.forEach(item => {
                let li = document.createElement('li')
                li.innerText = item.catname
                fragment.appendChild(li)
            })
            sidebarUl.appendChild(fragment)
        }
    })

    // 发请求渲染所有商品
    request({
        url: '/front/api/dish/getall'
    }).then(res => {
        // console.log(res);
        if (res.error_code === 200) {
            // 渲染界面
            // console.log(res.data);
            renderDish(res.data.dishes, contentOl)
        }
    })

    // 给搜索表单添加提交事件
    document.querySelector('.search form').onsubmit = function () {
        // 获取关键字
        let keywords = this.querySelector('[name="keywords"]').value
        // console.log(keywords);
        // 发请求获取对应的搜索商品
        request({
            url: '/front/api/dish/search/' + keywords
        }).then(res => {
            if (res.error_code === 200) {
                // console.log(res.data);
                renderDish(res.data.dishes, contentOl)
            }
        })
        return false
    }

    // 利用事件委托给所有分类li添加点击事件
    sidebarUl.onclick = function (e) {
        let target = e.target
        if (target.tagName === 'LI') {
            let catname = target.innerText
            // console.log(catname);
            request({
                url: '/front/api/dish/catDish/' + catname
            }).then(res => {
                if (res.error_code === 200) {
                    renderDish(res.data.dishes, contentOl)
                }
            })
        }
    }
}
// 封装渲染商品的函数
function renderDish(data, ele) {
    let olHTML = ''
    data.forEach(item => {
        olHTML += `
    <li>
        <img src="${item.imgpath}" alt="">
        <span>￥${item.price}.00</span>
        <input data-menuname="${item.name}" data-spec="${item.specifications}" data-kind="${item.kind}" data-id="${item._id}" type="button" value="选规格">
        <b>1</b>
    </li>
 `
    })
    ele.innerHTML = olHTML
}

// 封装规格和种类切换函数
function spedAndKindTab(e) {
    target = e.target
    if (target.tagName === 'P') {
        for (var a = 0; a < this.children.length; a++) {
            this.children[a].className = ''
        }
        target.className = 'active'
    }
}

